﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FizzWare.NBuilder;
using Microsoft.AspNetCore.Mvc;
using Kugar.AdminLte.Core.Test.Models;
using Kugar.AdminLte.Core.Test.Models.Home;
using Kugar.Core.BaseStruct;
using Kugar.Core.ExtMethod;
using Kugar.Core.Web;
using Kugar.Tool.Web.RequestFieldValidation;
using Kugar.Tool.Web.RequestFieldValidation.Rules;
using Kugar.UI.Web.AdminLTE.Controllers;
using Kugar.UI.Web.AdminLTE.Filters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Newtonsoft.Json.Linq;

namespace Kugar.AdminLte.Core.Test.Controllers
{
    //[AdminAuthority]
    [AdminAuthorizeScheme("system")]
    public class HomeController : WebUIBaseController
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public HomeController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        [HttpGet]
        public IActionResult Index()
        {
            ModelState.AddModelError("img","sdfssdf");
            ModelState.AddModelError("newupload","2222");
            ModelState.AddModelError("MultiImage","4444");
            //MsgBox("msg");
            //MsgBoxAndCallbackData("msg",new JObject(),true);
            //MsgBoxAndCallbackData("msg",new JObject(), false);
            //MsgBoxAndCloseModal("msg",true);
            //MsgBoxAndCloseModal("msg",false);
            //MsgBoxAndGoto("msg", "/Home/List");
            //MsgBoxAndRefresh("msg");
            //MsgBoxAndScript("msg", "console.log('message');");


            //Request.GetField("txt", "").NotEmpty("txt必填");

            ////Request.GetField("date", DateTime.MinValue, "yyyy-MM-dd HH:mm:ss").Must(x => x != DateTime.MinValue, "please select").EqualToField("startDt", errorMsg: "==startDt");

            ////Request.GetField<DateTime?>("startDt", null, "yyyy-MM-dd HH:mm:ss").Must(x => x.HasValue, "startDt必填").Must(x => x > DateTime.Now, "startDt>now").Must(x => x < DateTime.Now.AddDays(5), "StartDt<5d+now");
            ////Request.GetField<DateTime?>("endDt", null, "yyyy-MM-dd HH:mm:ss").Must(x => x.HasValue, "endDt必填").Must(x => x > DateTime.Now.AddDays(5), "endDt>5d+now").Must(x => x < DateTime.Now.AddDays(10), "EndDt<10d+now");

            ////Request.GetField("startVal", 0).GT(15, "startVal>15").LT(20, "startVal<20").EQ(18, "startVal=18");
            ////Request.GetField("endVal", 0).GTE(150, "endVal>=150").LTE(200, "endVal<=200").EqualToField("txt");

            //Request.GetField("txtBtn2", "").NotEmpty("必填");
            //Request.GetField("txtBtnID2", "").NotEmpty("ID!=null");

            ////Request.GetField("select", -1).Must(x => x != -1, "请选择");

            //报错
            //Request.GetArrayValueField("checkbox", Array.Empty<int>()).NotEmpty("必选项").WithElement((index, item) => item.GT(1, ">1"));
            //Request.GetField("checkbox", "").NotEmpty("必选");

            //Request.GetField("radio", "").NotEmpty("必选");

            //第二个errormsg覆盖第一个errormsg
            ////Request.GetField("pcd", "").NotEmpty("选择省市区");
            ////Request.GetField("addr", "").NotEmpty("填写地址");

            //Request.GetField("file", "").NotEmpty("please upload");
            //Request.GetField("img", "").NotEmpty("please upload");

            //报错
            ////Request.GetArrayValueField("multiFile", Array.Empty<string>()).NotEmpty("please upload");
            ////Request.GetArrayValueField("MultiImage", Array.Empty<string>()).NotEmpty("please upload");
            ////Request.GetField("multiFile", "").Exists("upload files");
            ////Request.GetField("MultiImage", "").Exists("upload images");

            //EQ不判断
            ////Request.GetField("Textarea", "").MinLength(5, "len>=5").EQ("aaaaaa", "value=aaaaaa");
            //Request.GetField("Textarea", "").NotEmpty("fill in").MaxLength(10, "len<=10");

            //Request.GetField("sum", "").NotEmpty("fill in").Length(20, 10, "len:10~20");

            //foreach (var key in new []{0,1,2})
            //{
            //    var index = key;
            //    Request.GetField($"cc_{index}", "").NotEmpty($"requiredcc{index}");
            //    Request.GetField($"rr_{index}", "").NotEmpty($"requiredrr{index}");
            //    Request.GetField($"tt_{index}", "").NotEmpty($"requiredtt{index}");
            //    Request.GetField($"ss_{index}", -1).Must(x => x != -1, $"requiredss{index}");
            //    Request.GetField($"tb_{index}", "").NotEmpty($"requiredtb{index}");
            //    Request.GetField($"tbID_{index}", "").NotEmpty($"requiredtbID{index}");
            //    Request.GetField($"ii_{index}", "").NotEmpty($"requiredii{index}");
            //    Request.GetField<DateTime?>($"dd_{index}", null, "yyyy-MM-dd").Must(x => x.HasValue, $"requireddd{index}");
            //}


            //var s = Request.HttpContext?.Connection?.RemoteIpAddress?.ToString();

            return View();
        }

        [HttpPost, ActionName("Index")]
        public IActionResult IndexPost()
        {
            //var txt = Request.GetField("txt", "").NotEmpty("必填项").EQ("aaa","=aaa").AddToModelState(ModelState).Value();
            //var txt = Request.GetField<decimal?>("txt", null).Must(x => x.HasValue, "必填").AddToModelState(ModelState).Value();
            //var txt = Request.GetField<bool?>("txt", null).Value();
            //var txt = Request.GetField("txt", "").Exists("txt不存在").AddToModelState(ModelState).Value();

            //var date = Request.GetField("date", DateTime.MinValue, "yyyy-MM-dd HH:mm:ss").Must(x => x != DateTime.MinValue, "please select").EqualToField("startDt", errorMsg: "==startDt").AddToModelState(ModelState).Value();

            //var startDt = Request.GetField<DateTime?>("startDt", null, "yyyy-MM-dd HH:mm:ss").Must(x => x.HasValue, "startDt必填").Must(x => x > DateTime.Now, "startDt>now").Must(x => x < DateTime.Now.AddDays(5), "startDt<5d+now").AddToModelState(ModelState).Value();
            //var endDt = Request.GetField<DateTime?>("endDt", null, "yyyy-MM-dd HH:mm:ss").Must(x => x.HasValue, "endDt必填").Must(x => x > startDt, "endDt>startDt").Must(x => x < DateTime.Now.AddDays(10), "endDt<10d+now").AddToModelState(ModelState).Value();

            //var startVal = Request.GetField("startVal", 0).GT(15, "startVal>15").LT(20, "startVal<20").EQ(18, "startVal=18").AddToModelState(ModelState).Value();
            //var endVal = Request.GetField("endVal", 0).GTE(150, "endVal>=150").LTE(200, "endVal<=200").AddToModelState(ModelState).Value();

            //var txtBtn2 = Request.GetField("txtBtn2", "").NotEmpty("必填").AddToModelState(ModelState).Value();
            //var txtBtnID2 = Request.GetField<int?>("txtBtnID2", null).Must(x => x.HasValue, "ID!=null").AddToModelState(ModelState).Value();

            //var select = Request.GetField("select", -1).Must(x => x != -1, "请选择").AddToModelState(ModelState).Value();

            //var checkBox = Request.GetArrayValueField("checkBox", Array.Empty<int>()).NotEmpty("必选项").WithElement((index, item) => item.GT(1, ">1")).AddToModelState(ModelState).Value();

            //var radio = Request.GetField("radio", -1).Must(x => x != -1, "请选择").GTE_When(1, select == -1).AddToModelState(ModelState).Value();

            //var pcd = Request.GetField("pcd", "").NotEmpty("选择省市区").AddToModelState(ModelState).Value();
            //var addr = Request.GetField("addr", "").NotEmpty("填写地址").AddToModelState(ModelState).Value();

            //var file = Request.GetField("file", "").NotEmpty("please upload").AddToModelState(ModelState).Value();
            //var img = Request.GetField("img", "").NotEmpty("please upload").AddToModelState(ModelState).Value();

            //var multiFile = Request.GetArrayValueField("multiFile", Array.Empty<string>()).NotEmpty("please upload").AddToModelState(ModelState).Value();
            //var MultiImage = Request.GetArrayValueField("MultiImage", Array.Empty<string>()).NotEmpty("please upload").AddToModelState(ModelState).Value();

            //var Textarea = Request.GetField("Textarea", "").MinLength(5, "len>=5").MaxLength(10, "len<=10").EQ("aaaaaa", "value=aaaaaa").AddToModelState(ModelState).Value();
            //var sum = Request.GetField("sum", "").Length(20, 10, "len:10~20").AddToModelState(ModelState).Value();

            //var keys = Request.Form.Keys.Where(x => x.StartsWith("dd_"));
            //foreach (var key in keys)
            //{
            //    var index = key.Split('_')[1];
            //    var cc = Request.GetField($"cc_{index}", "").Must(x => !string.IsNullOrWhiteSpace(x), $"requiredcc{index}").AddToModelState(ModelState).Value();
            //    var rr = Request.GetField($"rr_{index}", "").Must(x => !string.IsNullOrWhiteSpace(x), $"requiredrr{index}").AddToModelState(ModelState).Value();
            //    var tt = Request.GetField($"tt_{index}", "").Must(x => !string.IsNullOrWhiteSpace(x), $"requiredtt{index}").AddToModelState(ModelState).Value();
            //    var ss = Request.GetField($"ss_{index}", -1).Must(x => x != -1, $"requiredss{index}").AddToModelState(ModelState).Value();
            //    var tb = Request.GetField($"tb_{index}", "").Must(x => !string.IsNullOrWhiteSpace(x), $"requiredtb{index}").AddToModelState(ModelState).Value();
            //    var tbID = Request.GetField($"tbID_{index}", "").Must(x => !string.IsNullOrWhiteSpace(x), $"requiredtbID{index}").AddToModelState(ModelState).Value();
            //    var ii = Request.GetField($"ii_{index}", "").Must(x => !string.IsNullOrWhiteSpace(x), $"requiredii{index}").AddToModelState(ModelState).Value();
            //    var dd = Request.GetField<DateTime?>($"dd_{index}", null, "yyyy-MM-dd").Must(x => x.HasValue, $"requireddd{index}").AddToModelState(ModelState).Value();
            //}



            #region 

            //ModelState.AddModelError("txt", "testing...");
            //ModelState.AddModelError("select", "testing...");
            //ModelState.AddModelError("date", "testing...");
            //ModelState.AddModelError("startDt", "startDttesting...");
            //ModelState.AddModelError("endDt", "endDttesting...");
            //ModelState.AddModelError("startVal", "startValtesting...");
            //ModelState.AddModelError("endVal", "endValtesting...");
            //ModelState.AddModelError("checkbox", "testing...");
            //ModelState.AddModelError("txtBtn1", "txtBtn1testing...");
            //ModelState.AddModelError("txtBtn2", "txtBtn2testing...");
            //ModelState.AddModelError("txtBtnID2", "txtBtnID2testing...");
            //ModelState.AddModelError("txtBtn3", "txtBtn3testing...");
            //ModelState.AddModelError("radio", "testing...");
            //ModelState.AddModelError("file", "testing...");
            //ModelState.AddModelError("img", "testing...");
            //ModelState.AddModelError("pcd", "pcdtesting...");
            //ModelState.AddModelError("addr", "addrtesting...");
            //ModelState.AddModelError("multiFile", "testing...");
            //ModelState.AddModelError("MultiImage", "testing...");
            //ModelState.AddModelError("Textarea", "testing...");
            //ModelState.AddModelError("sum", "testing...");
            //ModelState.AddModelError("Container", "testing...");


            //var hideVal = Request.GetString("hideVal");
            //var txt = Request.GetString("txt");
            //var select = Request.GetInt("select", -1);
            //var date = Request.GetDateTimeNullable("date", "yyyy-MM-dd HH:mm:ss", null);
            //var startDt = Request.GetDateTimeNullable("startDt", "yyyy-MM-dd", null);
            //var endDt = Request.GetDateTimeNullable("endDt", "yyyy-MM-dd", null);
            //var startVal = Request.GetInt("startVal");
            //var endVal = Request.GetInt("endVal");
            //var checkbox = Request.GetString("checkbox");
            //var txtBtn2 = Request.GetString("txtBtn2");
            //var txtBtnID2 = Request.GetString("txtBtnID2");
            //var radio = Request.GetInt("radio");
            //var file = Request.GetString("file");
            //var img = Request.GetString("img");
            //var pcd = Request.GetString("pcd");
            //var addr = Request.GetString("addr");
            //var multiFile = Request.GetString("multiFile");
            //var MultiImage = Request.GetString("MultiImage");
            //var Textarea = Request.GetString("Textarea");
            //var sum = Request.GetString("sum");

            //var cc = Request.GetString("cc");
            //var rr = Request.GetString("rr");
            //var tt = Request.GetString("tt");
            //var ss = Request.GetString("ss");
            //var tb = Request.GetString("tb");
            //var tbID = Request.GetString("tbID");
            //var dd = Request.GetDateTimeNullable("dd", "yyyy-MM-dd", null);

            #endregion

            

            return View();
        }

        public IActionResult OuterBorderView()
        {
            return View();
        }


        [HttpGet]
        public IActionResult ModalWindow()
        {
            return View();
        }

        [HttpPost, ActionName("ModalWindow")]
        public IActionResult ModalWindowPost()
        {
            ModelState.AddModelError("modalTxt", "err");

            //MsgBox("msg");
            //MsgBoxAndCallbackData("msg",new JObject(),true);
            //MsgBoxAndCallbackData("msg", new JObject(), false);
            //MsgBoxAndCloseModal("msg", true);
            //MsgBoxAndCloseModal("msg",false);
            //MsgBoxAndGoto("msg", "/Home/ModalWindow");
            //MsgBoxAndRefresh("msg");
            //MsgBoxAndScript("msg", "console.log('message');");

            return View();
        }

        public IActionResult FileUploadView()
        {
            if (Request.Method.CompareTo("post",true))
            {
                var file = Request.GetFile();
            }
            

            return View();
        }


        public IActionResult List()
        {
            var hid = Request.GetString("hid");
            var levelOne = Request.GetInt("levelOne");
            var levelTwo = Request.GetInt("levelTwo");
            var ckb = Request.GetString("ckb");
            var dt = Request.GetDateTimeNullable("dt", "yyyy-MM-dd", null);
            var sDT = Request.GetDateTimeNullable("sDT", "yyyy-MM-dd", null);
            var eDT = Request.GetDateTimeNullable("eDT", "yyyy-MM-dd", null);
            var sVal = Request.GetString("sVal");
            var eVal = Request.GetString("eVal");
            var UserName = Request.GetString("UserName");
            var UserID = Request.GetString("UserID");
            var keyword = Request.GetString("keyword");
            var txt = Request.GetString("txt");


            var pageIndex = Request.GetInt("PageIndex", 1);


            var model = new Model_List();

            var list = Builder<TableTest>.CreateListOfSize(20).Build();

            model.Data = new VM_PagedList<TableTest>(list, pageIndex, 20, 1000);

            return View(model);
        }

        public ResultReturn Operation()
        {
            string methodName = Request.GetString("MethodName");
            var id = Request.GetInt("ID");

            switch (methodName)
            {
                case "show":
                    {
                        return new SuccessResultReturn(id);
                    }
                case "hide":
                    {
                        return new SuccessResultReturn(id);
                    }
                case "delete":
                    {
                        return new FailResultReturn($"禁止删除{id}");
                    }
                default:
                    {
                        return new FailResultReturn("未知操作");
                    }
            }
        }

        public IActionResult ModalList()
        {
            var levelOne = Request.GetInt("levelOne");
            var sDT = Request.GetDateTimeNullable("sDT", "yyyy-MM-dd", null);
            var eDT = Request.GetDateTimeNullable("eDT", "yyyy-MM-dd", null);
            var keyword = Request.GetString("keyword");


            var pageIndex = Request.GetInt("PageIndex", 1);


            var model = new Model_List();

            var list = Builder<TableTest>.CreateListOfSize(20).Build();

            model.Data = new VM_PagedList<TableTest>(list, pageIndex, 20, 1000);

            return View(model);
        }


        public IActionResult DataPicker()
        {
            var hid = Request.GetString("hid");
            var first = Request.GetInt("first");
            var sDT = Request.GetDateTimeNullable("sDT", "yyyy-MM-dd", null);
            var eDT = Request.GetDateTimeNullable("eDT", "yyyy-MM-dd", null);
            var keyword = Request.GetString("keyword");
            var txt = Request.GetString("txt");


            var pageIndex = Request.GetInt("PageIndex", 1);


            var model = new Model_List();

            var list = Builder<TableTest>.CreateListOfSize(20).Build();

            if (pageIndex > 1)
            {
                foreach (var item in list)
                {
                    item.UserName1 = item.UserName1 + "+" + pageIndex;
                }
            }

            model.Data = new VM_PagedList<TableTest>(list, pageIndex, 20, 1000);

            return View(model);
        }

        public IActionResult Tab()
        {
            var model = new Model_List();

            var list = Builder<TableTest>.CreateListOfSize(20).Build();

            model.Data = new VM_PagedList<TableTest>(list, 1, 20, 1000);

            return View(model);
        }

        [HttpPost, ActionName("Tab")]
        public IActionResult TabPost()
        {
            ModelState.AddModelError("txt", "testing...");
            ModelState.AddModelError("select", "testing...");
            ModelState.AddModelError("date", "testing...");
            ModelState.AddModelError("startDt", "startDttesting...");
            ModelState.AddModelError("endDt", "endDttesting...");


            var model = new Model_List();

            var list = Builder<TableTest>.CreateListOfSize(20).Build();

            model.Data = new VM_PagedList<TableTest>(list, 1, 20, 1000);

            return View(model);
        }

        [HttpPost]
        public ResultReturn UploadFile()
        {
            //var file = Request.Form.Files.FirstOrDefault();

            //if (file == null)
            //{
            //    return new FailResultReturn("未上传文件");
            //}

            //var path = $"/images/{file.GetRandomName()}";

            //using (var stream = new FileStream($"{_hostingEnvironment.WebRootPath}{path}", FileMode.Create))
            //{
            //    file.CopyTo(stream);
            //}

            //return new SuccessResultReturn(path);

            var file = Request.GetFile();

            var requestPath = $"/upload/test/{file.GetRandomName()}";
            var filePath = Path.Combine(Request.GetWebsitePath(), "wwwroot", requestPath.TrimStart('/'));

            file.SaveAsEx(filePath);

            //return new SuccessResultReturn("/images/24b1c0f7d80f4a7890481af5d4693952.jpeg");
            return new SuccessResultReturn(requestPath) {Message = "上传成功"};
            //return new FailResultReturn("error");
        }


        public IActionResult Child1()
        {
            return View();
        }

        public IActionResult Child2()
        {
            return View();
        }



        public IActionResult IFrameWindow()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }


}
